package com.doeis.minaserver.handler;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import com.doeis.log.QueueManager;
import com.doeis.minaserver.NettyServer;
import com.doeis.minaserver.packet.Packet;
import com.doeis.uwork.common.PacketUtil;
import com.doeis.uwork.entity.mongo.MinaPacketLog;

/*****
 * 空闲连接处理逻辑
 * ******/
public class IdlChannelHandlerAdapter extends ChannelHandlerAdapter {

	
	@Override
	public void write(ChannelHandlerContext ctx, Object msg,
			ChannelPromise promise) throws Exception {
		super.write(ctx, msg, promise);
		if(msg instanceof Packet ){
			//进行日志发送
			sendLog((Packet) msg, false,  ctx.channel().id().toString() );
		}
	
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		super.userEventTriggered(ctx, evt);
		if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state().equals(IdleState.READER_IDLE)) {
                System.out.println("READER_IDLE");
                // 超时关闭channel
                ctx.disconnect();
                ctx.channel().close();
            } else if (event.state().equals(IdleState.WRITER_IDLE)) {
                System.out.println("WRITER_IDLE");
            } else if (event.state().equals(IdleState.ALL_IDLE)) {
                System.out.println("ALL_IDLE"+ctx.name() +" "+ ctx.channel());
                ctx.disconnect();
                ctx.channel().close();
                // 发送心跳
//                ctx.channel().write("ping\n");
            }
        }
	}
	
	private void sendLog(Packet packet, boolean send, String sessionid){
		try{
			MinaPacketLog minaPacket = PacketUtil.cloneMinaPackett(packet, send);
			minaPacket.setSessionid(sessionid);
			QueueManager queueManager = NettyServer.getInstance().getT(QueueManager.class);
			if(queueManager!=null){
				queueManager.sendLog(minaPacket);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	
}
